package com.hujiang.basic.search.settings;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.hujiang.basic.search.common.exception.EsSettingException;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import com.hujiang.basic.search.handler.impl.model.BuildIndexRequest;
import com.hujiang.basic.search.util.IndexEsDao;

@Service
public class SettingsServiceImpl implements SettingsService {
    @Autowired
    private IndexEsDao esDao;

    @Override
    public String buildIndex(BuildIndexRequest req) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("/config/" + req.getIndexConifgFileName());
        InputStream inputStream = classPathResource.getInputStream();
        String indexConfig = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

        String indexName = this.buildIndexName(req.getIndexConifgFileName());
        String indexAlias = this.buildIndexAlias(req.getIndexConifgFileName());

        this.esDao.createIndex(indexName, indexConfig, indexAlias);

        return indexName;
    }

    @Override
    public List<String> getIndexConfigFileNames() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("/config/");
        File directory = classPathResource.getFile();
        return Arrays.asList(directory.listFiles()).stream().map(o -> o.getName()).collect(Collectors.toList());
    }

    private String buildIndexName(String indexConifgFileName) {
        String[] parts = indexConifgFileName.split("-");

        return parts[0] + "_" + DateTime.now().toString("yyyyMMddHHmmss");
    }

    private String buildIndexAlias(String indexConifgFileName) {
        String[] parts = indexConifgFileName.split("-");

        return parts[0];
    }
}
